from subprocess import PIPE ,Popen
import os
from sys import version_info

if version_info[0] == 2:
    input = raw_input

PROFILE_PATH = os.getenv("HOME")
PROFILE_DIR_PATH = os.path.join(PROFILE_PATH,".Qtornado")

if not os.path.exists(PROFILE_DIR_PATH):
    os.mkdir(PROFILE_DIR_PATH)

def _single(cls):
    instances = {}
    def __single(*args,**kargs):
        if cls not in instances:
            instances[cls] = cls(*args,**kargs)
        return instances[cls]
    return _single

# @_single
class SynDb(object):

    def __init__(self):
        self.base_path = PROFILE_DIR_PATH
        self.all_blogs = os.listdir(self.base_path)
        self.account_template = "{}::{}"

    def create_blog_account(self,blog_name,src,des):
        blog_file_path = os.path.join(self.base_path,blog_name)
        choice = ""
        
        if os.path.exists(blog_file_path):
            choice = input("\"{}\" is existed , will change it [y/n] ".format(blog_name))    
        else:
            choice = "y"

        if choice == "y":    
            account_str = self.account_template.format(src,des)
            print (blog_file_path)
            with open (blog_file_path,"w") as fp:
                fp.write(account_str)

    def get_blog_info(self,blog_name):
        blog_file_path = os.path.join(self.base_path,blog_name)
        res = None
        if os.path.exists(blog_file_path):
            with open(blog_file_path,"r") as fp:
                res = fp.read().strip().split("::")
                print (res)
        else:
            print("not found this blog's info  , if create [y/n] >")
            ch = input()[0]
            if ch == "y":
                name = input("blog name ,always is blog root dir 's name (no space and symbol) \n>").strip()
                src = input("blog local root path \n>")
                des = input("blog want to syn , implemented by scp , so you must type like this \nroot@isa.com:~/blogRootdir/\n>").strip()
                self.create_blog_account(name, src, des)
                print("create ok !!")
        return res


class Syn(SynDb):
    # def __init__(self):
    #     super(Syn, self).__init__()

    def syn(self,name=None):
        info = None
        if name ==None:
            all_blogs = self.all_blogs
            print(all_blogs)
            while 1:
                blog = input("which one to Syn ? \n>")
                if blog in all_blogs:
                    name = blog
                    break
                else:
                    self.get_blog_info(name)
            info  = self.get_blog_info(name)
        if info == None:
            print("exit .. from none")
            exit(0)
        self.syn_to_remote(*info)

    def syn_to_remote(self,src,des):
        p = Popen(["scp",src,des],shell=True,stdin=PIPE,stdout=PIPE)
        p.wait()
        if(p.returncode == 0):
            print("---- syn ----- [ok]")
        else:
            print("---- syn ----- [failed]")



